# -*- coding:utf-8 -*-
import requests
import logging
from dingtalkchatbot.chatbot import DingtalkChatbot
import zmail
import json
from collections import defaultdict
from config.config import *
from utils.cfg import GetConfig


class Notifier:
    """抽象通知类，定义了发送消息的基本方法"""

    def __init__(self, report_link):
        self.report_link = report_link
        self.test_counts = get_test_result_data()

    def send_message(self):
        raise NotImplementedError("子类必须实现send_message方法")


class DingTalkNotifier(Notifier):
    """钉钉通知器，用于发送钉钉群消息"""

    def __init__(self, webhook_url, report_link,secret):
        super().__init__(report_link)
        self.webhook_url = webhook_url
        self.secret = secret

    def send_message(self):

        data = f"""
        ### 接口自动化测试报告
        - **时间**：{time.strftime("%Y-%m-%d %H:%M:%S")}
        - **详情**：
            - 通过用例数: {self.test_counts['passed']}。
            - 失败用例数: {self.test_counts['failed']}。
            - 跳过用例数: {self.test_counts['skipped']}。
        - **点击查看测试报告**: [测试报告]({self.report_link})
        """
        ding = DingtalkChatbot(webhook=self.webhook_url, secret=self.secret)
        try:
            ding.send_markdown(title="测试报告", text=data, is_at_all=True)
            logging.info("5.发送钉钉消息成功")
        except Exception as e:
            logging.error(f"5.发送钉钉消息失败，原因是：{e}")


class WeChatWorkNotifier(Notifier):
    """企业微信通知器，用于发送企业微信群消息"""

    def __init__(self, webhook_url, report_link):
        super().__init__(report_link)
        self.webhook_url = webhook_url

    def send_message(self):
        headers = {'Content-Type': 'application/json'}
        data = {
            "msgtype": "markdown",
            "markdown": {
                "content": f"""
                    ### 接口自动化测试报告
    **时间**：{time.strftime("%Y-%m-%d %H:%M:%S")}
    **详情**：
    - 通过用例数: {self.test_counts['passed']}。
    - 失败用例数: {self.test_counts['failed']}。
    - 跳过用例数: {self.test_counts['skipped']}。
    **点击查看测试报告**: [测试报告]({self.report_link})
    """
            }
        }
        response = requests.post(self.webhook_url, headers=headers, data=json.dumps(data))
        if response.status_code == 200:
            logging.info("5.企业微信消息发送成功")
        else:
            logging.error(f"5.企业微信消息发送失败: {response.text}")


class EmailNotifier(Notifier):
    """邮件通知器，用于发送电子邮件"""

    def __init__(self, sender_email, sender_password, recipient_emails, report_link):
        super().__init__(report_link)
        self.sender_email = sender_email
        self.sender_password = sender_password
        self.recipient_emails = recipient_emails

    def send_message(self):
        server = zmail.server(username=self.sender_email, password=self.sender_password)

        # 创建HTML内容

        content = {
            "subject": "测试报告邮件发送",
            "content_text": f"""
接口自动化测试报告
时间：{time.strftime("%Y-%m-%d %H:%M:%S")}
详情：
    - 通过用例数: {self.test_counts['passed']}。
    - 失败用例数: {self.test_counts['failed']}。
    - 跳过用例数: {self.test_counts['skipped']}。
点击查看测试报告: [测试报告]({self.report_link})
            """
        }
        try:
            server.send_mail(self.recipient_emails, content)
            logging.info(f"5.发送邮件成功")

        except Exception as e:
            logging.error(f"5.发送邮件失败，原因是：{e}")


def get_test_result_data():
    """
    读取allure的json报告
    :return:
    """
    # 初始化计数器
    test_counts = defaultdict(int)

    # 遍历所有JSON文件
    for filename in os.listdir(RESULT_DIR):
        if filename.endswith('.json'):
            with open(os.path.join(RESULT_DIR, filename), 'r', encoding='utf-8') as file:
                data = json.load(file)
                # 统计用例状态
                status = data.get('status', 'unknown')
                test_counts[status] += 1

    return test_counts


def message_send():

    data = GetConfig(MESSAGE).get_message_config()

    """实际工作中需要有哪几个消息通知，这里就配置哪几个消息通知"""
    message_object = [
        DingTalkNotifier(webhook_url=data["dingding"]["web_hook"], report_link=REPORT_LINK,secret=data["dingding"]["secret"]),
        WeChatWorkNotifier(webhook_url=data["wechat"]['web_hook'], report_link=REPORT_LINK),
        EmailNotifier(data["email"]["sender_email"], data["email"]["sender_password"], eval(data["email"]["recipient_emails"]), report_link=REPORT_LINK)
    ]

    for mo in message_object:
        mo.send_message()


# 使用示例
if __name__ == "__main__":
    # 假设这里已经定义了必要的参数
    report_link = "http://example.com/test-report"
    message = "这是测试报告的摘要信息。"
    web_hook = "https://oapi.dingtalk.com/robot/send?access_token=5b16df829e8af426eafeb1b2ae2a895b44991269c2fd2c3c502e42be12aa3feb"

    ding = DingTalkNotifier(webhook_url=web_hook, report_link=report_link)
    ding.send_message()

    wechat_web_hook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=95265406-bcc4-4b06-83f0-70c9586022d7"
    wechat = WeChatWorkNotifier(webhook_url=wechat_web_hook, report_link=report_link)
    wechat.send_message()

    sender_email = "18883609193@163.com"
    sender_password = "FNb7hMbYqzBnPwbf"
    email = EmailNotifier(sender_email, sender_password, "18883609193@163.com", report_link=report_link)

    email.send_message()
